package com.dm.voicesubtitle.gui;

import com.dm.voicesubtitle.config.AppConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 字幕显示面板
 */
public class SubtitlePanel extends JPanel {
    private static final Logger logger = LoggerFactory.getLogger(SubtitlePanel.class);
    
    private final ConcurrentLinkedQueue<SubtitleItem> subtitleQueue;
    private final List<SubtitleItem> activeSubtitles;
    private final Timer animationTimer;
    private final Timer cleanupTimer;
    
    private final AppConfig.DisplayConfig displayConfig;
    
    public SubtitlePanel() {
        this.subtitleQueue = new ConcurrentLinkedQueue<>();
        this.activeSubtitles = new ArrayList<>();
        this.displayConfig = AppConfig.getInstance().getDisplayConfig();
        
        // 初始化动画定时器
        this.animationTimer = new Timer(16, this::updateAnimation); // 60 FPS
        this.animationTimer.start();
        
        // 初始化清理定时器
        this.cleanupTimer = new Timer(1000, this::cleanupExpiredSubtitles);
        this.cleanupTimer.start();
        
        initializePanel();
    }
    
    /**
     * 初始化面板
     */
    private void initializePanel() {
        setOpaque(false);
        setLayout(null); // 使用绝对布局
        
        // 设置背景色
        setBackground(Color.decode(displayConfig.getBackgroundColor()));
        
        // 设置字体
        setFont(new Font(displayConfig.getFontFamily(), Font.BOLD, displayConfig.getFontSize()));
    }
    
    /**
     * 添加字幕
     */
    public void addSubtitle(String text, String languageCode) {
        if (text == null || text.trim().isEmpty()) {
            return;
        }
        
        SubtitleItem item = new SubtitleItem(text, languageCode, System.currentTimeMillis());
        subtitleQueue.offer(item);
        
        logger.debug("添加字幕: {} (语言: {})", text, languageCode);
    }
    
    /**
     * 更新动画
     */
    private void updateAnimation(ActionEvent e) {
        // 处理新添加的字幕
        SubtitleItem newItem;
        while ((newItem = subtitleQueue.poll()) != null) {
            activeSubtitles.add(newItem);
        }
        
        // 重新绘制
        repaint();
    }
    
    /**
     * 清理过期的字幕
     */
    private void cleanupExpiredSubtitles(ActionEvent e) {
        long currentTime = System.currentTimeMillis();
        java.util.Iterator<SubtitleItem> iterator = activeSubtitles.iterator();
        while (iterator.hasNext()) {
            SubtitleItem item = iterator.next();
            if (currentTime - item.getCreateTime() > displayConfig.getSubtitleDuration()) {
                iterator.remove();
            }
        }
    }
    
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        
        // 绘制背景
        g2d.setColor(Color.decode(displayConfig.getBackgroundColor()));
        g2d.fillRect(0, 0, getWidth(), getHeight());
        
        // 绘制字幕
        drawSubtitles(g2d);
    }
    
    /**
     * 绘制字幕
     */
    private void drawSubtitles(Graphics2D g2d) {
        if (activeSubtitles.isEmpty()) {
            return;
        }
        
        int panelWidth = getWidth();
        int panelHeight = getHeight();
        int yOffset = 50;
        
        for (SubtitleItem item : activeSubtitles) {
            // 计算字幕位置
            String text = item.getText();
            FontMetrics fm = g2d.getFontMetrics();
            int textWidth = fm.stringWidth(text);
            
            // 居中显示
            int x = (panelWidth - textWidth) / 2;
            int y = panelHeight - yOffset;
            
            // 绘制文字阴影
            g2d.setColor(Color.BLACK);
            g2d.drawString(text, x + 2, y + 2);
            
            // 绘制主文字
            Color textColor = getTextColorForLanguage(item.getLanguageCode());
            g2d.setColor(textColor);
            g2d.drawString(text, x, y);
            
            yOffset += 40; // 下一个字幕的位置
        }
    }
    
    /**
     * 根据语言获取文字颜色
     */
    private Color getTextColorForLanguage(String languageCode) {
        switch (languageCode) {
            case "zh-CN":
                return Color.decode("#FF6B6B"); // 红色
            case "en-US":
                return Color.decode("#4ECDC4"); // 青色
            case "ja-JP":
                return Color.decode("#45B7D1"); // 蓝色
            default:
                return Color.decode(displayConfig.getTextColor());
        }
    }
    
    /**
     * 清除所有字幕
     */
    public void clearSubtitles() {
        subtitleQueue.clear();
        activeSubtitles.clear();
        repaint();
    }
    
    /**
     * 获取当前字幕数量
     */
    public int getSubtitleCount() {
        return subtitleQueue.size() + activeSubtitles.size();
    }
    
    /**
     * 字幕项类
     */
    private static class SubtitleItem {
        private final String text;
        private final String languageCode;
        private final long createTime;
        
        public SubtitleItem(String text, String languageCode, long createTime) {
            this.text = text;
            this.languageCode = languageCode;
            this.createTime = createTime;
        }
        
        // Getter方法
        public String getText() { return text; }
        public String getLanguageCode() { return languageCode; }
        public long getCreateTime() { return createTime; }
    }
    
    /**
     * 清理资源
     */
    public void cleanup() {
        if (animationTimer != null) {
            animationTimer.stop();
        }
        if (cleanupTimer != null) {
            cleanupTimer.stop();
        }
    }
} 